package com.atguigu.edu.realtime.dwd.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.common.base.BaseApp;
import com.atguigu.edu.realtime.common.constant.Constant;
import com.atguigu.edu.realtime.common.util.DateFormatUtil;
import com.atguigu.edu.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

public class DwdTrafficUvDetail extends BaseApp {


    public static void main(String[] args) {
        new DwdTrafficUvDetail().start(
                11101,
                4,
                "uv_source"
                , Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //kafkaStrDS.print("page");
        //将流中的"last_page_id"为null的数据过滤掉,并将数据进行转化jsonStr-JsonObj
        SingleOutputStreamOperator<JSONObject> firstPageDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(jsonStr);
                        String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");
                        if (lastPageId != null) {
                            out.collect(jsonObject);
                        }
                    }
                }
        );
        //按照mid进行分组
        KeyedStream<JSONObject, String> keyByDS = firstPageDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        //使用flink状态编程，过滤出独立访客记录
        SingleOutputStreamOperator<JSONObject> filterDS = keyByDS.filter(
                new RichFilterFunction<JSONObject>() {
                    ValueState<String> lastValueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("lastValueState", String.class);
                        valueStateDescriptor
                                .enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L))  //设置状态存活时间为1天
                                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite).build());
                        lastValueState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public boolean filter(JSONObject jsonObject) throws Exception {
                        String curVisitDt = DateFormatUtil.tsToDate(jsonObject.getLong("ts"));
                        String lastVisitDt = lastValueState.value();
                        if (lastVisitDt == null || DateFormatUtil.dateToTs(lastVisitDt) < DateFormatUtil.dateToTs(curVisitDt)) {
                            lastValueState.update(curVisitDt);
                            return true;
                        }
                        return false;
                    }
                }
        );
        filterDS.print("filterDS");
        //将独立访客数据写入到kafka的主题中
        filterDS.map(jsonObj->JSON.toJSONString(jsonObj)).sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_UNIQUE_VISITOR_DETAIL));
    }
}
